<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page -->
 <route lang="jsonc" type="home">
{
  "layout": "tabbar",
  "style": {
    // 'custom' 表示开启自定义导航栏，默认 'default'
    "navigationStyle": "custom",
    "navigationBarTitleText": "首页"
  }
}
</route>

<script lang="ts" setup>
import { onShow } from '@dcloudio/uni-app'
import { tabbarStore } from '@/layouts/fg-tabbar/tabbar'

import { useSafeAreaInsets } from '@/utils/useSafeAreaInsets'

defineOptions({
  name: 'Home',
})

const { safeAreaInsets } = useSafeAreaInsets()

// 定义响应式变量
const backgroundColor = ref('#f7f7f7')
const fontColor = ref('#000')
const fixed = ref(false)

const itemsApp = ref([
  {
    type: 'image',
    icon: 'https://cj-hz-default.oss-cn-hangzhou.aliyuncs.com/weixin/legalaffairs.png',
    text: '企业法务',
    url: '/pages-sub/legalaffairs/index',
  },
  {
    type: 'image',
    icon: 'https://cj-hz-default.oss-cn-hangzhou.aliyuncs.com/weixin/personnel.png',
    text: '人事合规',
    url: '/pages-sub/personnel/index',
  },
  {
    type: 'image',
    icon: 'https://cj-hz-default.oss-cn-hangzhou.aliyuncs.com/weixin/financetaxation.png',
    text: '财税合规',
    url: '/pages-sub/financetaxation/index',
  },
  {
    type: 'image',
    icon: 'https://cj-hz-default.oss-cn-hangzhou.aliyuncs.com/weixin/businessaccount.png',
    text: '工商记账',
    url: '/pages-sub/businessaccount/index',
  },
  {
    type: 'image',
    icon: 'https://cj-hz-default.oss-cn-hangzhou.aliyuncs.com/weixin/employment.png',
    text: '企业用工',
    url: '/pages-sub/employment/index',
  },
  {
    type: 'image',
    icon: 'https://cj-hz-default.oss-cn-hangzhou.aliyuncs.com/weixin/mediapublic.png',
    text: '媒体舆情',
    url: '/pages-sub/mediapublic/index',
  },
  {
    type: 'image',
    icon: 'https://cj-hz-default.oss-cn-hangzhou.aliyuncs.com/weixin/marketing.png',
    text: '营销传播',
    url: '/pages-sub/marketing/index',
  },
  {
    type: 'image',
    icon: 'https://cj-hz-default.oss-cn-hangzhou.aliyuncs.com/weixin/outsea.png',
    text: '企业出海',
    url: '/pages-sub/outsea/index',
  },
  {
    type: 'image',
    icon: 'https://cj-hz-default.oss-cn-hangzhou.aliyuncs.com/weixin/purchase.png',
    text: '企业采购',
    url: '/pages-sub/purchase/index',
  },
  {
    type: 'image',
    icon: 'https://cj-hz-default.oss-cn-hangzhou.aliyuncs.com/weixin/intellectualproperty.png',
    text: '知识产权',
    url: '/pages-sub/intellectualproperty/index',
  },
  {
    type: 'image',
    icon: 'https://cj-hz-default.oss-cn-hangzhou.aliyuncs.com/weixin/projectapplication.png',
    text: '项目申报',
    url: '/pages-sub/projectapplication/index',
  },
  {
    type: 'image',
    icon: 'https://cj-hz-default.oss-cn-hangzhou.aliyuncs.com/weixin/all.png',
    text: '全部',
    url: '/pages/legalservice/index',
    isTabbar: true,
  },
])

const pageSize = 16
const pagedItems = computed(() => {
  const pages = []
  for (let i = 0; i < itemsApp.value.length; i += pageSize) {
    pages.push(itemsApp.value.slice(i, i + pageSize))
  }
  return pages
})

// 用于控制swiper高度
const swiperHeight = ref('auto')
const currentSwiperIndex = ref(0)
const current = ref<number>(0)

const swiperList = ref([
  'https://cj-hz-default.oss-cn-hangzhou.aliyuncs.com/weixin/heard_img.png',
])

function handleClick(e) {
  console.log(e)
}
function onChange(e) {
  // console.log(e)
}

// 确保首页在tabbar中被正确选中
function ensureHomeSelected() {
  // 如果当前是首页，确保tabbar选中首页
  const pages = getCurrentPages()
  if (pages.length > 0) {
    const currentPage = pages[pages.length - 1]
    if (currentPage.route === 'pages/index/index') {
      tabbarStore.setCurIdx(0) // 首页通常是第一个tab
    }
  }
}

// 测试 uni API 自动引入
onLoad(() => {
  ensureHomeSelected()
})

// 当页面重新显示时，确保tabbar状态正确
onShow(() => {
  ensureHomeSelected()
  // 页面显示后需要计算高度
  nextTick(() => {
    updateSwiperHeight(currentSwiperIndex.value)
  })
})

// 当swiper切换时
function onSwiperChange(e) {
  currentSwiperIndex.value = e.detail.current
  updateSwiperHeight(e.detail.current)
}

// 更新swiper高度
function updateSwiperHeight(index) {
  // 使用nextTick确保DOM已更新
  nextTick(() => {
    const query = uni.createSelectorQuery()
    query
      .select(`.swiper-item-${index} .grid-container`)
      .boundingClientRect((data) => {
        if (data && typeof data === 'object' && 'height' in data) {
          console.log('高度数据:', data.height)
          // 设置一个最小高度，确保即使内容很少也有一定的高度
          const height = data.height < 100 ? '400rpx' : `${data.height + 20}px`
          swiperHeight.value = height
        }
      })
      .exec()
  })
}

function onScrollEvent(e) {
  // 获取滚动位置
  const scrollTop = e.detail.scrollTop
  handleScroll(scrollTop)
}

// 滚动处理函数
function handleScroll(scrollTop: number) {
  if (scrollTop <= 50) {
    fontColor.value = '#fff'
    backgroundColor.value = ''
  }
  else if (scrollTop < 100) {
    const rate = scrollTop / 100
    backgroundColor.value = `rgba(255,255,255, ${rate})`
    fontColor.value = `rgba(0,0,0, ${rate})`
  }
  else {
    backgroundColor.value = 'rgba(255,255,255, 1)'
    fontColor.value = 'rgba(0,0,0, 1)'
  }
  // console.log('页面滚动：', scrollTop, fontColor.value, backgroundColor.value)
}

function gotoAlova() {
  uni.navigateTo({
    url: '/pages/about/alova',
  })
}

// 应用跳转 - 使用异步导航
async function goToDetail(item) {
  console.log(item)
  if (!item.url) {
    return
  }

  if (item.isTabbar) {
    uni.switchTab({
      url: item.url,
      fail: (error) => {
        console.log(error, 'aaaaaaa')
      },
    })
  }
  else {
    uni.navigateTo({
      url: item.url,
      fail: (fallbackError) => {
        console.log(fallbackError, 'Fallback navigation failed')
      },
    })
  }
}
</script>

<template>
  <scroll-view style="height: calc(100vh - 60rpx)" scroll-y>
    <CosHeader
      title=""
      :fixed="fixed"
      :font-color="fontColor"
      :background-color="backgroundColor"
      background-image=""
      :is-show-back="false"
      :is-show-left="true"
      :is-show-right="false"
      :jump-map="{ back: 'navigateTo', home: 'switchTab' }"
      :default-menu-width="280"
    >
      <template #left>
        <view class="w-495rpx flex items-center justify-between pl-2">
          <view>
            <image
              src="https://cj-hz-default.oss-cn-hangzhou.aliyuncs.com/weixin/logo.png"
              mode="scaleToFill"
              class="h-96rpx w-168rpx"
            />
          </view>
          <view class="flex items-center rounded-2xl bg-white px-30rpx py-4rpx">
            <text class="iconfont icon-sousuo" :style="{ color: fontColor, fontSize: '36rpx' }" />
            <text class="ml-1 text-size-xl c-black">搜索</text>
          </view>
        </view>
      </template>
    </CosHeader>
    <view class="bg-#f7f7f7">
      <view class="p-4">
        <wd-swiper
          v-model:current="current"
          :list="swiperList"
          autoplay
          image-mode="widthFix"
          @click="handleClick"
          @change="onChange"
        />
      </view>
      <view class="p-4">
        <swiper
          :current="currentSwiperIndex"
          :style="{ height: swiperHeight }"
          :autoplay="false"
          :indicator-dots="false"
          indicator-color="rgba(0, 0, 0, 0.3)"
          indicator-active-color="#0052d9"
          @change="onSwiperChange"
        >
          <swiper-item
            v-for="(page, pageIndex) in pagedItems"
            :key="pageIndex"
            :class="`swiper-item-${pageIndex}`"
          >
            <view class="grid-container">
              <wd-grid :column="4">
                <view
                  v-for="(item, index) in page"
                  :key="index"
                  class="grid-item-wrapper"
                  @click="goToDetail(item)"
                >
                  <wd-grid-item :text="item.text" :use-icon-slot="true" icon-size="72rpx">
                    <template #icon>
                      <text
                        v-if="item.type === 'font'"
                        :class="item.icon"
                        class="text-[72rpx] text-blue-600 leading-none"
                      />
                      <image
                        v-else
                        :src="item.icon"
                        alt=""
                        class="h-[72rpx] w-[72rpx] object-contain"
                        :lazy-load="true"
                      />
                    </template>
                  </wd-grid-item>
                </view>
              </wd-grid>
            </view>

          </swiper-item>
        </swiper>
        <view class="mb-4">
          <view>
            <view class="mb-3 text-lg font-bold">
              热门服务
            </view>

            <!-- <view class="flex gap-3">
              <view class="flex-1 rounded bg-white p-3 shadow">
                <view class="text-base font-semibold">
                  法务咨询
                </view>
                <view class="mt-1 text-sm text-gray-500">
                  自营律师团队，在线答疑解惑
                </view>
              </view>
              <view class="flex flex-1 flex-col gap-3">
                <view class="rounded bg-white p-3 shadow">
                  <view class="text-base font-semibold">
                    合同定制审核
                  </view>
                  <view class="mt-1 text-sm text-gray-500">
                    百万服务经验，精准把握风险
                  </view>
                </view>
                <view class="rounded bg-white p-3 shadow">
                  <view class="text-base font-semibold">
                    企业债务纠纷
                  </view>
                  <view class="mt-1 text-sm text-gray-500">
                    百万服务经验，精准把握风险
                  </view>
                </view>
              </view>
            </view> -->
            <view class="align-center flex">
              <image
                src="https://cj-hz-default.oss-cn-hangzhou.aliyuncs.com/weixin/hot_one.png"
                mode="scaleToFill"
                class="h-232rpx"
              />
              <view>
                <image
                  src="https://cj-hz-default.oss-cn-hangzhou.aliyuncs.com/weixin/hot_two.png"
                  mode="scaleToFill"
                  class="h-108rpx w-368rpx"
                />
                <image
                  src="https://cj-hz-default.oss-cn-hangzhou.aliyuncs.com/weixin/hot_three.png"
                  mode="scaleToFill"
                  class="mt-10rpx h-108rpx w-368rpx"
                />
              </view>
            </view>
          </view>
          <view class="mt-4">
            <view class="mb-3 text-lg font-bold">
              创接专属服务
            </view>
            <view class="grid grid-cols-2 gap-3">
              <view class="relative left-0 top-0 text-center">
                <image class="absolute inset-0 h-full w-full" src="https://cj-hz-default.oss-cn-hangzhou.aliyuncs.com/weixin/cj_ser_one.png" mode="aspectFill" :lazy-load="true" />
                <view class="relative z-10 p-3 text-left">
                  <view class="text-size-sm font-500">专业版咨询服务</view>
                  <view class="text-size-2xs text-[#666666] font-500">助力企业降本增效</view>
                  <wd-button size="small" custom-class="bg-[#506BFF] mt-20rpx">去咨询</wd-button>
                </view>
              </view>
              <view class="relative left-0 top-0 text-center">
                <image class="absolute inset-0 h-full w-full" src="https://cj-hz-default.oss-cn-hangzhou.aliyuncs.com/weixin/cj_ser_two.png" mode="aspectFill" :lazy-load="true" />
                <view class="relative z-10 p-3 text-left">
                  <view class="text-size-sm font-500">人事合规SaaA</view>
                  <view class="text-size-2xs text-[#666666] font-500">人事合规管理平台</view>
                  <wd-button size="small" custom-class="bg-[#147AFF] mt-20rpx">去查看</wd-button>
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="h-120rpx"></view>
      </view>
    </view>
  </scroll-view>
</template>

<style lang="scss" scoped>
.grid-item-wrapper {
  position: relative;
  width: 100%;
  cursor: pointer;
}

/* 添加点击效果 */
.grid-item-wrapper:active {
  opacity: 0.7;
}

.grid-container {
  background-color: #fff;
  padding: 20rpx;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
}
</style>
